package com.bysc.userservice.websocket;

import com.alibaba.fastjson.JSON;
import com.bysc.commonutils.enums.NoticeEnum;
import com.bysc.commonutils.message.LoginMessage;
import com.bysc.commonutils.message.NotificationMessage;
import com.bysc.commonutils.utils.DateUtil;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.commonutils.utils.RandomUtil;
import com.bysc.userservice.utils.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ServerEndpoint(value = "/websocketservice/{token}", subprotocols = {"protocol"})
@Component
public class WebSocketServer extends AbstractWebSocketHandler {

    /**
     * 记录当前在线连接数
     */
    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 存放所有在线的客户端
     */
    private static final Map<String, Session> clients = new ConcurrentHashMap<>();
    /**
     * 使用ApplicationContextUtil获取ThreadPoolExecutor实例
     */
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        String userId;
        String nickname;
        if (!StringUtils.isEmpty(token) && !"-1".equals(token)) {
            userId = JwtUtils.getMemberIdByJwtToken(token);
            nickname = JwtUtils.getNicknameByJwtToken(token);
        } else {//无token则自动生成6位数id
            userId = RandomUtil.getSixBitRandom();
            nickname = "同学";
            System.out.println(userId);
            onlineCount.incrementAndGet(); // 在线数加1
            sendToLogin(userId, nickname);
            return;
        }
        if (clients.get(userId) == null) {
            onlineCount.incrementAndGet(); // 在线数加1
        }
        System.out.println(userId);
        clients.put(userId, session);
        sendToLogin(userId, nickname);
        log.info("有新连接加入：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        if (onlineCount.get() > 0) {
            onlineCount.decrementAndGet(); // 在线数减1
        }
        clients.entrySet().removeIf(entry -> entry.getValue().equals(session));
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     *                当业务改动数据时，可以主动发消息（不需要客户端主动请求）
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
//        this.sendMessage(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    public Integer getOnLine() {
        return onlineCount.get();
    }


    public void sendToLogin(String userId, String nickname) {
        Session toSession = clients.get(userId);
        if (toSession == null) {
            return;
        }
        LoginMessage loginMessage = new LoginMessage(NoticeEnum.SYSTEM.getValue(), getOnLine(), nickname);
        String message = JSON.toJSONString(loginMessage);
        this.threadPoolExecutor = ApplicationContextUtil.getBean(ThreadPoolExecutor.class);
        CompletableFuture.runAsync(() -> toSession.getAsyncRemote().sendText(message), threadPoolExecutor);
    }

    public void sendToOne(NotificationMessage notificationMessage) {

        Session toSession = clients.get(notificationMessage.getNoticedUserId());
        if (toSession == null) {
            return;
        }
        String message = JSON.toJSONString(notificationMessage);
        this.threadPoolExecutor = ApplicationContextUtil.getBean(ThreadPoolExecutor.class);
        CompletableFuture.runAsync(() -> toSession.getAsyncRemote().sendText(message), threadPoolExecutor);
    }

    public void sendToAll(NotificationMessage notificationMessage) {
        clients.values().forEach(toSession -> {
            String message = JSON.toJSONString(notificationMessage);
            this.threadPoolExecutor = ApplicationContextUtil.getBean(ThreadPoolExecutor.class);
            CompletableFuture.runAsync(() -> toSession.getAsyncRemote().sendText(message), threadPoolExecutor);
        });
    }

    public void sendToClub(NotificationMessage notificationMessage, ArrayList<String> ids) {
        ids.forEach(id -> {
            Session toSession = clients.get(id);
            if (toSession == null) {
                return;
            }
            String message = JSON.toJSONString(notificationMessage);
            this.threadPoolExecutor = ApplicationContextUtil.getBean(ThreadPoolExecutor.class);
            CompletableFuture.runAsync(() -> toSession.getAsyncRemote().sendText(message), threadPoolExecutor);
        });
    }

    public void sendTime(Date date) {
        clients.values().forEach(toSession -> {
            String message = JSON.toJSONString(DateUtil.formatDate(date, "yyyy-MM-dd HH:mm:ss"));
            this.threadPoolExecutor = ApplicationContextUtil.getBean(ThreadPoolExecutor.class);
            CompletableFuture.runAsync(() -> toSession.getAsyncRemote().sendText(message), threadPoolExecutor);
        });
    }
}